<template>
  <div>
    <el-tree ref="treeRef" :data="permissions" show-checkbox :props="{ label: 'name' }" default-expand-all node-key="id"
      check-strictly></el-tree>
    <div class="footer">
      <el-button @click="$emit('close')">取消</el-button>
      <el-button type="primary" @click="hSubmit">确定</el-button>
    </div>

  </div>
</template>

<script>
import { getPermissionList } from '@/api/permissions';
import { assignPermissions, getRoleDetailById } from '@/api/role';
import { tranListToTreeData } from '@/utils';

export default {
  props: {
    id: {
      type: String,
      requires: true
    }
  },
  data() {
    return {
      permissions: []
    }
  },
  created() {
    this.loadPermissions()
    this.loadRoleDetail()
  },
  methods: {
    async loadPermissions() {
      try {
        const res = await getPermissionList()
        console.log('res', res);
        this.permissions = tranListToTreeData(res.data)

      } catch (error) {

      }
    },
    async loadRoleDetail() {
      try {
        const res = await getRoleDetailById(this.id)
        console.log(res);
        this.$refs.treeRef.setCheckedKeys(res.data.permIds)
      } catch (error) {

      }
    },
    async hSubmit() {
      try {
        const key = this.$refs.treeRef.getCheckedKeys()
        const res = await assignPermissions({
          id: this.id,
          permIds: key
        })
        this.$message.success(res.message)
        this.$emit('close')
      } catch (error) {
        this.$message.error(error.message)
      }


    }

  }
}
</script>

<style scoped lang="scss">
.footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 30px;
}
</style>